package com.rpoonolly.simplegame;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;

import com.rpoonolly.simplegame.core.CountingInputManager;

public class SimpleCountingInputManager<E extends Enum<E>> implements KeyListener, CountingInputManager<E> {
	private Map<Integer, E> keyActionMap;
	private Map<E, Boolean> inputStateMap;
	private Map<E, Integer> inputCountMap;
	
	public SimpleCountingInputManager(Map<Integer, E> keyToActionMap) {
		keyActionMap = keyToActionMap;
		
		inputStateMap = new HashMap<E, Boolean>(keyToActionMap.size());
		inputCountMap = new HashMap<E, Integer>(keyToActionMap.size());
		for(E action : keyActionMap.values()) {
			inputStateMap.put(action, false);
			inputCountMap.put(action, 0);
		}
	}

	@Override
	public boolean isActionRequested(E action) {
		return inputStateMap.get(action);
	}

	@Override
	public void clearActionRequests() {
		for(E action : keyActionMap.values())
			inputStateMap.put(action, false);
	}

	@Override
	public int getActionCount(E action) {
		return inputCountMap.get(action);
	}

	@Override
	public void clearActionCount(E action) {
		inputCountMap.put(action, 0);
	}

	@Override
	public void clearAllActionCounts() {
		for(E action : inputCountMap.keySet())
			inputCountMap.put(action, 0);
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		E action = keyActionMap.get(e.getKeyCode());
		if (action == null) return;
		
		inputStateMap.put(action, true);
	}

	@Override
	public void keyReleased(KeyEvent e) {
		E action = keyActionMap.get(e.getKeyCode());
		if (action == null) return;
		
		if (inputStateMap.get(action)) {
			int actionCount = inputCountMap.get(action);
			actionCount++;
			inputCountMap.put(action, actionCount);
		}
		
		inputStateMap.put(action, false);
	}

	@Override
	public void keyTyped(KeyEvent e) {}
}
